package com.zrrd.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zrrd.reggie.bean.Category;
import com.zrrd.reggie.common.R;
import com.zrrd.reggie.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    //分页查分类
    @GetMapping("/page")
    public R<Page> page(Integer page, Integer pageSize) {
        //创建分页对象
        Page<Category> pageInfo = new Page<>(page, pageSize);
        //创建条件构造器
        QueryWrapper<Category> wapper = new QueryWrapper<>();
        wapper.orderByDesc("sort");
        //执行分页
        categoryService.page(pageInfo, wapper);
        //返回数据
        return R.success(pageInfo);
    }

    //新增分类
    @PostMapping
    public R<String> addCategory(@RequestBody Category category) {
        return categoryService.save(category) ? R.success("新增分类成功") : R.error("新增分类失败");
    }

    //修改分类
    @PutMapping
    public R<String> updateCategory(@RequestBody Category category) {
        return categoryService.updateById(category) ? R.success("修改分类成功") : R.error("修改分类失败");
    }

    //删除分类
    @DeleteMapping
    public R<String> deleteCategory(Long id) {
        return categoryService.removeById(id) ? R.success("删除分类成功") : R.error("删除分类失败");
    }

    //展示菜品分类
    @Cacheable(value = "categoryCache")
    @GetMapping("/list")
    public R<List<Category>> list(Integer type) {
        QueryWrapper<Category> wapper = new QueryWrapper<>();
        if (type != null) {
            wapper.eq("type", type);
        }
        return R.success(categoryService.list(wapper));
    }

}
